package org.tp.framework.adapt;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * 请求参数适配器
 */
public class RequestParamAdapt {
	/**
	 * 将请求中的参数与指定方法中的参数对应
	 * 
	 * @param methodParamMap
	 * @param paramTypes
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	public static Object[] getParam(Map<String, Object> methodParamMap, Class<?>[] paramTypes,
			HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		if (paramTypes == null) {
			return null;
		}

		Object[] params = new Object[paramTypes.length];

		List<String> paramValues = convertParam(request, methodParamMap);
		for (int i = 0; i < paramTypes.length; i++) {
			Class<?> paraType = paramTypes[i];
			if (paraType.isAssignableFrom(request.getClass())) {
				params[i] = request;
				continue;
			}

			if (paraType.isAssignableFrom(response.getClass())) {
				params[i] = response;
				continue;
			}
			if (paraType.isAssignableFrom(session.getClass())) {
				params[i] = session;
				continue;
			}

			params[i] = paramValues.get(i);

		}

		return params;
	}

	/**
	 * 参数列表参数与请求中的对应 拿到响应数据
	 * 
	 * @param request
	 * @param methodParamMap
	 * @return
	 */
	private static List<String> convertParam(HttpServletRequest request, Map<String, Object> methodParamMap) {
		List<String> paramValues = new ArrayList<>();
		Map<String, String[]> reqParams = request.getParameterMap();
		for (String key : methodParamMap.keySet()) {
			if (reqParams.containsKey(key)) {
				paramValues.add(reqParams.get(key)[0]);
			}
		}

		return paramValues;
	}

}
